//
//  FANComposeView.swift
//  Weibo - Swift
//
//  Created by user on 16/4/25.
//  Copyright © 2016年 user. All rights reserved.
//

import UIKit
import pop

class FANComposeView: UIView {
    
    lazy var boardImageView:UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    lazy var composeArray:[FANComposeButton] = [FANComposeButton]()
    
    lazy var array:[FANCompose] = {
    
        return self.getComposeArrayInfo()
    
    }()
    
    var target:UIViewController?
    
    override init(frame: CGRect) {
        
        super.init(frame:frame)
        
        setupUI()
    }

    func show(target:UIViewController?){
        
        target?.view.addSubview(self)
        
        self.target = target
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setImageOriginal()->UIImage{
        
        let window = UIApplication.sharedApplication().keyWindow
        
        let screenRect = UIScreen.mainScreen().bounds
        
        UIGraphicsBeginImageContextWithOptions(screenRect.size, true, 1)
        
        window?.drawViewHierarchyInRect(screenRect, afterScreenUpdates: false)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image
    }
    
    func setupUI(){
        
        self.frame = UIScreen.mainScreen().bounds
        
        let image = setImageOriginal().applyLightEffect()
        
        let imageView = UIImageView(image: image)
        
        
        self.addSubview(imageView)
        
        self.addSubview(boardImageView)
        
        boardImageView.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self)
            
            make.top.equalTo(100)
        }
        
        addComposeButton()
    }
    
    override func didMoveToSuperview() {
        
        super.didMoveToSuperview()
        
        for (index,value) in composeArray.enumerate(){
            
            animation(value, index: index, up: true)
        }
    }
    
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        super.touchesBegan(touches, withEvent: event)
        
        for (index,value) in self.composeArray.reverse().enumerate(){
            
            self.animation(value, index: index, up: false)
        }

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.removeFromSuperview()

        }
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        <#code to be executed after a specified delay#>
//                        })
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            <#code to be executed after a specified delay#>
//            });
        
//        self.removeFromSuperview()

        
    }
    
   @objc private func didComposeClick(button:FANComposeButton){
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for value in self.composeArray{
                
                value.alpha = 0.01
                
                if value == button{
                    
                    value.transform = CGAffineTransformMakeScale(2, 2)
                    
                }else{
                    
                    value.transform = CGAffineTransformMakeScale(0.01, 0.01)
                }
            }
            
            
            }) { (_) -> Void in
                
                
                let model = self.array[button.tag]
                
//                let className = NSStringFromClass(FANComposeViewController.self)
                
//                let xxx = NSStringFromClass(className)
                
//                print(className)
                
                let type = NSClassFromString(model.className!)! as! UIViewController.Type
                
                let Vc = type.init()

                self.target?.presentViewController(UINavigationController(rootViewController: Vc), animated: true, completion: { () -> Void in
                    
                    self.removeFromSuperview()

                })
                

        }
    }
    
    func animation(value:FANComposeButton, index:Int ,up:Bool){
        
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        anim.toValue = NSValue(CGPoint: CGPointMake(value.center.x, value.center.y + (up ? -350 : 350)))
        
        anim.springBounciness = 8
        
        anim.springSpeed = 10
        
        anim.beginTime = Double(index)*0.025 + CACurrentMediaTime()
        
        value.pop_addAnimation(anim, forKey: "haha")
        
    }
    
    func addComposeButton(){
        
        let buttonW:CGFloat = 80
        
        let buttonH:CGFloat = 110
        
        let margin = (UIScreen.mainScreen().bounds.size.width - buttonW*3)/4
        
        let array = getComposeArrayInfo()
        
        for (index,value) in array.enumerate(){
            
            let col = CGFloat(index % 3)
            
            let row = CGFloat(index / 3)
            
            let button = FANComposeButton(titleColor: UIColor.darkGrayColor(), fontSize: 14)
            
            button.addTarget(self, action: "didComposeClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            button.tag = index
            
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            
            button.setTitle(value.title, forState: .Normal)
            
            button.frame.size = CGSizeMake(buttonW, buttonH)
            
            button.frame.origin.x = col * buttonW + (col + 1) * margin
            
            button.frame.origin.y = row * buttonH + ScreenH
            
            composeArray.append(button)
            
            self.addSubview(button)
        }
        
       
    }
    
    func getComposeArrayInfo()->[FANCompose]{
        
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        
        let array = NSArray(contentsOfFile: path!)
        
        var tempArray = [FANCompose]()
        
        for value in array!{
            
            let model = FANCompose(dict:value as! [String : AnyObject])
            
            tempArray.append(model)
        }
        
        return tempArray
    }
  
    
  

}
